package com.qd.qx.ui.module1;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.universaladapter.ViewHolderHelper;
import com.aspsine.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.qd.common.base.BaseActivity;
import com.qd.common.baseapp.AppManager;
import com.qd.common.commonutils.SPUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.qx.R;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.app.AppConstants;
import com.qd.qx.bean.ChatConfig;
import com.qd.qx.bean.GroupConfigBean;
import com.qd.qx.bean.MembersBean;
import com.qd.qx.bean.PeopleBean;
import com.qd.qx.bean.SingleChatConfigBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.db.bean.MsgList;
import com.qd.qx.im.ChatInfoUtils;
import com.qd.qx.im.ImRxBus;
import com.qd.qx.ui.main.activity.ChatActivity;
import com.qd.qx.ui.module2.TongXunLuSelectActivity;
import com.qd.chatui.util.MyUtils;
import com.qd.qx.widget.GreenSwitchView;
import com.wevey.selector.dialog.DialogOnItemClickListener;
import com.wevey.selector.dialog.NormalSelectionDialog;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/31
 * Function：聊天更多详情页面
 */
public class ChatMoreActivity extends BaseActivity {


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvMore)
    TextView tvMore;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.ircv)
    IRecyclerView ircv;
    @BindView(R.id.tv_groupname)
    TextView tvGroupname;
    @BindView(R.id.fl_groupname)
    FrameLayout flGroupname;
    @BindView(R.id.iv_erweima)
    ImageView ivErweima;
    @BindView(R.id.fl_grouperweima)
    FrameLayout flGrouperweima;
    @BindView(R.id.tv_groupnotice)
    TextView tvGroupnotice;
    @BindView(R.id.fl_groupnotice)
    FrameLayout flGroupnotice;
    @BindView(R.id.tv_groupmanager)
    TextView tvGroupmanager;
    @BindView(R.id.ll_group)
    LinearLayout llGroup;
    @BindView(R.id.tv_lookchatinfo)
    TextView tvLookchatinfo;
    @BindView(R.id.gsv_chattop)
    GreenSwitchView gsvChattop;
    @BindView(R.id.gsv_nosing)
    GreenSwitchView gsvNosing;
    @BindView(R.id.tv_saveshow)
    TextView tvSaveshow;
    @BindView(R.id.gsv_save)
    GreenSwitchView gsvSave;
    @BindView(R.id.tv_clearchat)
    TextView tvClearchat;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.rl_groupmore_show)
    RelativeLayout rlGroupmoreshow;
    @BindView(R.id.rlGroupMline)
    RelativeLayout rlGroupMline;
    CommonRecycleViewAdapter adapter;
    List<MembersBean.DataBean> list = new ArrayList<>();
    String jid = "";
    ChatConfig chatConfig = new ChatConfig();//设置bean
    boolean isSingleChat = true;//单聊  群聊 标志
    String localAccoutId;//已有的人 单人转群聊用
    String localName;//已有的人名字 单人转群聊用

    /**
     * 入口
     */
    public static void startAction(Activity activity, String jid) {
        Intent intent = new Intent(activity, ChatMoreActivity.class);
        intent.putExtra("jid", jid);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_chatmore;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if ((intent.getFlags() | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) > 0) {
            if (android.os.Build.VERSION.SDK_INT >= 19 && !isTaskRoot()) {
                ActivityManager tasksManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                tasksManager.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_NO_USER_ACTION);
            }
        }
    }

    @Override
    public void initView() {
        ivMore.setVisibility(View.GONE);
        jid = getIntent().getStringExtra("jid");
        if (jid.contains("conference")) {
            isSingleChat = false;
        } else {
            isSingleChat = true;
        }
        chatConfig.setUserCode(UserData.getInstance().getRefCode());
        chatConfig.setOnlyChatId(ChatInfoUtils.getInstance().splitShortId(jid));
        initAdapter();
    }

    /**
     * 群聊相关操作
     */
    private void groupAction() {
        llGroup.setVisibility(View.VISIBLE);

        ChatInfoUtils.getInstance().getGroupInfo(jid, new ChatInfoUtils.ChatInfoCallBack() {
            @Override
            public void callBack(Object object) {
                if (null == object) {
                    ToastUitl.showShort("数据有误");
                } else {
                    MembersBean bean = (MembersBean) object;
                    list.clear();
                    list.addAll(bean.getData());
                    setShowList();
                    adapter.replaceAll(list);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        //获取群聊相关配置
        ChatInfoUtils.getInstance().getGroupConfig(UserData.getInstance().getRefCode(), jid, new ChatInfoUtils.ChatInfoCallBack() {
            @Override
            public void callBack(Object object) {
                if (null == object) {
                    ToastUitl.showShort("数据有误");
                } else {
                    GroupConfigBean bean = (GroupConfigBean) object;
                    chatConfig.setIsSave(bean.getData().getIsCommonUse());
                    chatConfig.setIsRing(bean.getData().getIsNotDisturb());
                    chatConfig.setIsShowMember(bean.getData().getIsDisplayMember());
                    switchViewListener(chatConfig);
                }
            }
        });
    }

    /**
     * 单聊相关
     */
    private void singLeChatAction() {
        llGroup.setVisibility(View.GONE);
        ChatInfoUtils.getInstance().querySingleChatConfig(UserData.getInstance().getRefCode(), jid, new ChatInfoUtils.ChatInfoCallBack() {
            @Override
            public void callBack(Object object) {
                if (null == object) {
                    ToastUitl.showShort("数据有误");
                } else {
                    SingleChatConfigBean bean = (SingleChatConfigBean) object;
                    chatConfig.setIsSave(bean.getData().getIsCommonUse());
                    chatConfig.setIsRing(bean.getData().getIsNotDisturb());
                    switchViewListener(chatConfig);
                }
            }
        });
    }


    /**
     * 设置聊天相关开关显示
     */
    private void setChatConfigShow() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        setShowData();
    }

    /**
     * 设置需要刷新的数据
     */
    private void setShowData() {
        if (null != tvTitle) {
            if (isSingleChat) {
                //单聊
                singLeChatAction();
                final MsgList msgList = ChatInfoUtils.getInstance().getDbHelper().getMsgList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(), jid);
                if (null != msgList) {
                    tvTitle.setText(msgList.getRealName());
                    ChatInfoUtils.getInstance().getUserInfo(msgList.getTo_name(), new ChatInfoUtils.ChatInfoCallBack() {
                        @Override
                        public void callBack(Object object) {
                            String img = "";
                            String account = "";
                            if (null != object) {
                                List<PeopleBean> imgList = (List<PeopleBean>) object;
                                img = imgList.get(0).getHeaderImg();
                                account = imgList.get(0).getAccount();
                            } else {
                                img = "http://img5.imgtn.bdimg.com/it/u=1455435328,1387112107&fm=200&gp=0.jpg";
                            }
                            MembersBean.DataBean bean = new MembersBean.DataBean();
                            bean.setName(msgList.getRealName());
                            bean.setHeadImg(img);
                            bean.setAccount(account);
                            localAccoutId = ChatInfoUtils.getInstance().splitShortId(jid);//单聊转群聊用 im登陆账号 拼音名字
                            localName = msgList.getRealName();//单聊转群聊用 真实昵称
                            list.clear();
                            list.add(bean);
                            setShowList();
                            adapter.replaceAll(list);
                            adapter.notifyDataSetChanged();
                        }
                    });
                }

            } else {
                //群聊
                groupAction();
                if (!TextUtils.isEmpty(jid)) {
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            final String strTitle = MyXMPPTCPConnection.getInstance().getGroupNickName(jid);
                            if (!TextUtils.isEmpty(strTitle)) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (null != tvTitle) {
                                            tvTitle.setText(strTitle);
                                        }
                                        if (null != tvGroupname) {
                                            tvGroupname.setText(strTitle);
                                        }
                                    }
                                });

                            }
                        }
                    }.start();

                    //设置群描述
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            final String desc = MyXMPPTCPConnection.getInstance().getGroupDesc(jid);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (null != tvGroupnotice) {
                                        if (!TextUtils.isEmpty(desc)) {
                                            tvGroupnotice.setText(desc);
                                        } else {
                                            tvGroupnotice.setText("未设置");
                                        }
                                    }

                                }
                            });

                        }
                    }.start();

                }
            }
        }

    }

    @OnClick({R.id.ivBack, R.id.fl_groupname, R.id.fl_grouperweima, R.id.fl_groupnotice, R.id.tv_groupmanager, R.id.tv_lookchatinfo, R.id.tv_clearchat, R.id.tv_delete, R.id.rl_groupmore_show})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.fl_groupname:
                EditGroupNameActivity.startAction(this, jid);
                break;
            case R.id.fl_grouperweima:
                break;
            case R.id.fl_groupnotice:
                EditGroupDescActivity.startAction(this, jid);
                break;
            case R.id.tv_groupmanager:
                ChatChangeOwnerActivity.startAction(this, jid);
                break;
            case R.id.tv_lookchatinfo:
                break;
            case R.id.tv_clearchat:
                clearChatInfo();
                break;
            case R.id.tv_delete:
                exitGroup();
                break;
            case R.id.rl_groupmore_show:
                //查看更多群成员
                GroupMembersShowActivity.startAction(this, jid, list);
                break;
        }
    }

    /**
     * 设置转换群主 是否显示
     *
     * @param isShow
     */
    private void setGroupmanagerIsShow(boolean isShow) {
        if (isShow) {
            rlGroupMline.setVisibility(View.VISIBLE);
            tvGroupmanager.setVisibility(View.VISIBLE);
        } else {
            rlGroupMline.setVisibility(View.GONE);
            tvGroupmanager.setVisibility(View.GONE);
        }
    }

    private void initAdapter() {
        adapter = new CommonRecycleViewAdapter<MembersBean.DataBean>(this, R.layout.chatmore_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final MembersBean.DataBean bean) {
                ImageView imageView = helper.getView(R.id.ivImg);
                TextView tvName = helper.getView(R.id.tvName);

                switch (null == bean.getName() ? "" : bean.getName()) {
                    case "add":
                        tvName.setText("");
                        imageView.setImageResource(R.drawable.kuang_jia);
                        break;
                    case "minus":
                        tvName.setText("");
                        imageView.setImageResource(R.drawable.kuang_jian);
                        break;
                    default:
                        tvName.setText(bean.getName() + "");
                        MyUtils.displayUserHeader(ChatMoreActivity.this, imageView, bean.getHeadImg(), bean.getName());
                        break;
                }

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (bean.getName()) {
                            case "add":
                                TongXunLuSelectActivity.startAction(ChatMoreActivity.this, "0", "通讯录", jid, localAccoutId, localName);
                                break;
                            case "minus":
                                ChatRemoveActivity.startAction(ChatMoreActivity.this, jid);
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
        };
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        ircv.setLayoutManager(gridLayoutManager);
        adapter.addAll(list);
        ircv.setAdapter(adapter);
    }


    /**
     * 滑动按钮监听事件
     */
    private void switchViewListener(ChatConfig chatConfig) {


        //置顶
        if (jid.equals(SPUtils.getSharedStringData(AppConstants.CHAT_MESSAGE_TOP))) {
            gsvChattop.setOpened(true);
        } else {
            gsvChattop.setOpened(false);
        }

        //免打扰
        if (chatConfig.getIsRing() == 1) {
            gsvNosing.setOpened(true);
        } else {
            gsvNosing.setOpened(false);
        }
        //常用联系人
        if (chatConfig.getIsSave() == 1) {
            gsvSave.setOpened(true);
        } else {
            gsvSave.setOpened(false);
        }


        gsvChattop.setOnStateChangedListener(new GreenSwitchView.OnStateChangedListener() {
            @Override
            public void toggleState(boolean flag) {
                if (flag) {
                    SPUtils.setSharedStringData(AppConstants.CHAT_MESSAGE_TOP, jid);
                } else {
                    SPUtils.setSharedStringData(AppConstants.CHAT_MESSAGE_TOP, "");
                }
                MsgList msgBean = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(), jid);
                String top_time = "";
                if (null != msgBean) {
                    if (TextUtils.isEmpty(msgBean.getTop_time())) {
                        top_time = System.currentTimeMillis() + "";
                    } else {
                        top_time = "";
                    }
                    MyXMPPTCPConnection.getInstance().getDbHelper().resetTopTime(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(),
                            msgBean.getMsg_list_id(), top_time);
                }

            }
        });
        gsvNosing.setOnStateChangedListener(new GreenSwitchView.OnStateChangedListener() {
            @Override
            public void toggleState(boolean flag) {
                if (isSingleChat) {
                    setSingleConfig();
                } else {
                    setGroupConfig();
                }

            }
        });

        gsvSave.setOnStateChangedListener(new GreenSwitchView.OnStateChangedListener() {
            @Override
            public void toggleState(boolean flag) {
                if (isSingleChat) {
                    setSingleConfig();
                } else {
                    setGroupConfig();
                }
            }
        });
    }

    /**
     * 设置群的配置
     */
    private void setGroupConfig() {
        if (gsvNosing.isOpened()) {
            chatConfig.setIsRing(1);
        } else {
            chatConfig.setIsRing(0);
        }

        if (gsvSave.isOpened()) {
            chatConfig.setIsSave(1);
        } else {
            chatConfig.setIsSave(0);
        }
        ChatInfoUtils.getInstance().updateGroupConfig(chatConfig.getUserCode(), chatConfig.getOnlyChatId(), chatConfig.getIsRing(),
                chatConfig.getIsShowMember(), chatConfig.getIsSave(), new ChatInfoUtils.ChatInfoCallBack() {
                    @Override
                    public void callBack(Object object) {
                        if (null != object) {
                            ToastUitl.showShort("设置成功");
                        }
                    }
                });


    }

    /**
     * 设置单聊配置
     */
    private void setSingleConfig() {
        if (gsvNosing.isOpened()) {
            chatConfig.setIsRing(1);
        } else {
            chatConfig.setIsRing(0);
        }

        if (gsvSave.isOpened()) {
            chatConfig.setIsSave(1);
        } else {
            chatConfig.setIsSave(0);
        }
        ChatInfoUtils.getInstance().updataSingleChatConfig(chatConfig.getUserCode(), chatConfig.getOnlyChatId(), chatConfig.getIsRing(),
                chatConfig.getIsSave(), new ChatInfoUtils.ChatInfoCallBack() {
                    @Override
                    public void callBack(Object object) {
                        if (null != object) {
                            ToastUitl.showShort("设置成功");
                        }
                    }
                });


    }

    /**
     * 清空聊天记录
     */
    private void clearChatInfo() {
        ArrayList<String> list = new ArrayList<>();
        list.add("清空聊天记录");
        NormalSelectionDialog selectionDialog = new NormalSelectionDialog.Builder(ChatMoreActivity.this)
                .setItemTextColor(Color.parseColor("#ec4c4b"))
                .setCancleTextColor(Color.parseColor("#333333"))
                .setOnItemListener(new DialogOnItemClickListener() {
                    @Override
                    public void onItemClick(Button button, int position) {
                        MsgList msgList = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(), jid);
                        if (null != msgList) {
                            MyXMPPTCPConnection.getInstance().getDbHelper().clearChatMessage(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(), msgList.getMsg_list_id());
                        }
                        ImRxBus.getInstance().post(new Message());//刷新会话聊表
                        finish();
                    }
                }).build();
        selectionDialog.setDataList(list);

        selectionDialog.show();
    }

    /**
     * 退出群组
     */
    private void exitGroup() {
        ArrayList<String> list = new ArrayList<>();
        list.add("确定");
        NormalSelectionDialog selectionDialog = new NormalSelectionDialog.Builder(ChatMoreActivity.this)
                .setTitleText("退出后不会通知群聊中其他成员").setlTitleVisible(true)
                .setTitleTextColor(Color.parseColor("#333333"))
                .setItemTextColor(Color.parseColor("#ec4c4b"))
                .setCancleTextColor(Color.parseColor("#333333"))
                .setOnItemListener(new DialogOnItemClickListener() {
                    @Override
                    public void onItemClick(Button button, int position) {
                        MyXMPPTCPConnection.getInstance().quitRoom(jid);
                        MsgList msgList = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id(), jid);
                        if (null != msgList) {
                            MyXMPPTCPConnection.getInstance().getDbHelper().deleteChat(msgList.getMsg_list_id());
                        }
                        AppManager.getAppManager().finishActivity(ChatActivity.class);
                        finish();
                    }
                }).build();
        selectionDialog.setDataList(list);

        selectionDialog.show();
    }


    private void setShowList() {
        MembersBean.DataBean beanAdd = new MembersBean.DataBean();
        beanAdd.setName("add");
        list.add(beanAdd);
        if (isSingleChat) {

        } else {
            //第一个人是群主
            if (0 != list.size() && list.get(0).getName().equals(UserData.getInstance().getRealName())) {
                MembersBean.DataBean beanRemove = new MembersBean.DataBean();
                beanRemove.setName("minus");
                list.add(beanRemove);
                setGroupmanagerIsShow(true);
            } else {
                setGroupmanagerIsShow(false);
            }
            setGroupmanagerIsShow(true);
        }


//        if (null != list && list.size() > 40) {
//            rlGroupmoreshow.setVisibility(View.VISIBLE);
//        }
    }


}
